package cn.edu.xmu.oomall.activity.model.bo.strategy;

import cn.edu.xmu.oomall.activity.model.vo.StrategyVo;

import java.util.ArrayList;
import java.util.List;

public class ShareCalc {
    public static Long calcPoint(List<StrategyVo> originStrategy, Long price, Long oldQuantity, Long orderItemQuantity) {
        int left = -1, right = -1, total = Math.toIntExact(oldQuantity + orderItemQuantity);
        Long pointAmount = 0L;
        Integer strategySize = originStrategy.size();
        List<StrategyVo> strategy = new ArrayList<>(originStrategy);
        for (int i =0;i<strategySize;i++) {
            if (left == -1) {
                if (strategy.get(i).getQuantity() > oldQuantity ) {
                    left = i;
                }
                else if(i == strategy.size() - 1) {
                    left = i + 1;
                }
            }
            if (right == -1) {
                if (strategy.get(i).getPercentage() > total) {
                    right = i;
                } else if (i == strategy.size() - 1) {
                    right = i + 1;
                }
            }
        }
        strategy.add(strategy.get(strategySize - 1));

        if (left == right) {
            pointAmount += price * orderItemQuantity * strategy.get(left).getPercentage() / 1000;
        }
        else {
            pointAmount += price * (strategy.get(left).getQuantity()) * strategy.get(left).getPercentage() / 1000;
            pointAmount += price * (total - strategy.get(right - 1).getQuantity()) * strategy.get(right).getPercentage() / 1000;
            for (int i = left + 1; i < right; i++) {
                pointAmount += price * (strategy.get(i).getQuantity() - strategy.get(i - 1).getQuantity()) * strategy.get(i).getPercentage() / 1000;
            }
        }
        return pointAmount;
    }
}
